package com.heima.app.gateway.filter;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 通过request判断请求地址
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        // 地址是登录，放行
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }
        // 地址不是登录，获取请求头的token
        String token = request.getHeaders().getFirst("token");
        // 判断token是否为空
        if (StringUtils.isEmpty(token)) {
            // 空，返回401  没有授权
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 不为空，校验token的合法性和有效性
        try {
            int result = AppJwtUtil.verifyToken(AppJwtUtil.getClaimsBody(token));
            if (result == 1 || result == 2) {// 1 2 过期
                // 校验不通过，返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } catch (Exception e) {
            throw new RuntimeException("请登录后查看");
        }
        // 校验通过，放行
        return chain.filter(exchange);
    }

    /**
     * 排序，值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
